<script setup>
import { Search } from '@element-plus/icons-vue'
import { GetListDetailAPI, GetBomAPI } from '@/api/material/common'
import Converter from '@/components/XiaoheComponents/order/converter'
import Production from './production.vue'
import { getStockInfoBomAPI } from '@/api/warehouse/outbound/producfield.js'

const { proxy } = getCurrentInstance()

// 生产计划弹窗
const productionOrderIsShow = ref(false)
const supplierIsShow = ref(false)
// 封装 方法 字典查询
const {
  subcontracting_order_type // 委外类型
} = proxy.useDict('subcontracting_order_type')

const props = defineProps({
  data: {
    type: Object,
    default: {}
  },
  // 是否禁用
  db: {
    type: Boolean,
    default: false
  }
})

const tabs = ref('单据明细')

// 物料弹窗
const materialShow = ref(false)
const materialShow2 = ref(false)
// bom弹窗
const bomShow = ref(false)

// 加工商弹窗
const converterShow = ref(false)

// 表单Ref
const ruleFormRef = ref(null)

// 是否禁用物料
const materialDis = ref(false)

// 表单字段
const ruleForm = reactive({
  converterDict: '', // 加工商名称
  orderMaterialDetailList: [] //  warehouseWeight 出库数量
})

// 校验
const rules = reactive({
  subcontractingType: [{ required: true, message: '请选择BOM编码', trigger: 'change' }],
  bomCode: [{ required: true, message: '请选择BOM编码', trigger: 'change' }],
  demandTime: [{ required: true, message: '请选择需求时间', trigger: 'change' }],
  // associatedDocNum: [{ required: true, message: '请选择关联单号', trigger: 'blur' }],
  subcontractingWeight: [{ required: true, message: '请填写委外数量', trigger: 'change' }],
  supplierName: [{ required: true, message: '请选择供应商', trigger: 'blur' }],
  machiningPrice: [{ required: true, message: '请输入加工单价', trigger: 'blur' }]
})

const dis = computed(() => {
  if (ruleForm.subcontractingType == 1) {
    return ruleForm.associatedDocNum
  } else {
    return ruleForm.materialCode
  }
})

// 生产计划单
const productionSub = obj => {
  // console.log(obj)
  ruleForm.associatedDocNum = obj.planAssociatedCode
  ruleForm.materialType = obj.materialType
  ruleForm.materialId = obj.planMaterialId
  ruleForm.materialCode = obj.planMaterialCode
  ruleForm.materialName = obj.planMaterialName
  ruleForm.materialSpec = obj.planMaterialSpec
  ruleForm.materialTypeDict = obj.planMaterialTypeDict || '后端没给'
  productionOrderIsShow.value = false
}

// 供应商选择
const supplierSub = val => {
  ruleForm.supplierName = val.supplierName
  ruleForm.supplierId = val.id
  supplierIsShow.value = false
}

// 委外类型选择
const typeChange = (val = 1) => {
  if (val == 1) {
    materialDis.value = true
    ruleForm.materialType = ''
    ruleForm.materialId = ''
    ruleForm.materialCode = ''
    ruleForm.materialName = ''
    ruleForm.materialSpec = ''
    ruleForm.materialTypeDict = ''
  } else {
    materialDis.value = false
  }
}

// 物料选择
const materialSelsct = val => {
  ruleForm.materialType = val.materialType
  ruleForm.materialId = val.materialId
  ruleForm.materialCode = val.materialCode
  ruleForm.materialName = val.materialName
  ruleForm.materialSpec = val.materialSpec
  ruleForm.materialTypeDict = val.materialTypeDict
  materialShow.value = false
  getList()
}

const bomSelList = ref([])

// 查询 Bom
const getList = async () => {
  console.log('ssss====')
  try {
    const res = await GetBomAPI({
      pageNum: 1,
      pageSize: 9999,
      materialCode: ruleForm.materialCode
    })

    bomSelList.value = res.rows
  } catch (err) {
    console.log('err', err)
  } finally {
  }
}

// BOM选择
const bomSelsct = val => {
  if (!val) return
  const result = bomSelList.value.find(t => t.bomCode == ruleForm.bomCode)
  if (!result) return
  ruleForm.bomId = result.bomId
  ruleForm.materialCode = result.materialCode
  ruleForm.materialName = result.materialName
  ruleForm.materialSpec = result.materialSpec
  ruleForm.materialTypeDict = result.bomType == 3 ? '半成品' : '成品'
  ruleForm.materialType = result.bomType
  ruleForm.orderMaterialDetailList.map(item => {
    item.bomProportion = result.bomProportion
  })
  bomShow.value = false

  // 查询bom详情(材料BOM)
  getBomList(ruleForm.bomId)
}

/**
 * 委外数量回车
 */
const subcontractingWeightkeyup = async () => {
  ruleForm.materialDetailList = []
  try {
    if (!ruleForm.materialCode) return proxy.warningMsg('请先选择物料编码!')
    const res = await getStockInfoBomAPI({
      materialCode: ruleForm.materialCode,
      planWeight: ruleForm.subcontractingWeight
    })
    // res.data.forEach(item => {
    //   ruleForm.list.push(item)
    // })
    ruleForm.materialDetailList = res.data
  } catch (error) {}
}

// 加工商选择
const converterSelsct = val => {
  ruleForm.converterDict = val.converterName
  ruleForm.converterId = val.id
  converterShow.value = false
}

// 材料bom
const getBomList = async bomId => {
  try {
    const res = await GetListDetailAPI({ pageNum: 1, pageSize: 99999, bomId })
    ruleForm.orderMaterialDetailList = res.data
    //   计算每个需求量
    ruleForm.orderMaterialDetailList.forEach(item => (item.需求量 = item.inventory * item.bomDetailDosage))
  } catch {
  } finally {
  }
}

/**
 * 物料信息弹窗
 */
const addTable = () => {
  materialShow2.value = true
}

/**
 * 物料信息确认
 */
const materialSub2 = obj => {
  const arr = obj.list.map(item => item)
  arr.forEach(items => {
    ruleForm.orderMaterialDetailList.push(items)
  })
  materialShow2.value = false
}

/**
 * 类型
 */
const isTypeList = async () => {
  ruleForm.orderMaterialDetailList = []
  try {
    const res = await getStockInfoBomAPI({
      materialCode: ruleForm.materialCode,
      planWeight: ruleForm.subcontractingWeight,
      isTwoFlag: true
    })
    ruleForm.orderMaterialDetailList = res.data
  } catch (error) {}
}

// 提交
const submit = async () => {
  return new Promise((resolve, reject) => {
    ruleFormRef.value.validate((valid, fields) => {
      if (!valid) {
        proxy.warningMsg('请填写完整')
        resolve(false)
        return
      }
      resolve(ruleForm)
    })
  })
}

// 回显
const initData = async () => {
  for (let Key in props.data) {
    ruleForm[Key] = props.data[Key]
  }
  console.log(ruleForm)
  if (ruleForm.materialCode) {
    await getList()
  }
  // if (ruleForm.bomCode) {
  //   await bomSelsct()
  // }
}
initData()
defineExpose({ submit })
</script>
<template>
  <div class="app-container">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" inline label-width="90px" status-icon>
      <el-form-item label="委外订单号" prop="subcontractingOrderNum">
        <el-input clearable v-model="ruleForm.subcontractingOrderNum" disabled />
      </el-form-item>
      <el-form-item label="关联单号" prop="associatedDocNum">
        <el-input clearable v-model="ruleForm.associatedDocNum" disabled />
      </el-form-item>
      <el-form-item label="物料名称">
        <el-input clearable v-model="ruleForm.materialName" disabled />
      </el-form-item>
      <el-form-item label="物料规格">
        <el-input clearable v-model="ruleForm.materialSpec" disabled />
      </el-form-item>
      <el-form-item label="点数">
        <el-input clearable v-model="ruleForm.pointPosition" />
      </el-form-item>
      <el-form-item label="物料类别">
        <el-input clearable v-model="ruleForm.materialTypeDict" disabled />
      </el-form-item>
      <!-- @change="bomSelsct" -->
      <el-form-item label="BOM" prop="bomCode" v-if="ruleForm.subcontractingType != '3'">
        <el-select
          v-model="ruleForm.bomCode"
          :disabled="ruleForm.status != 1 && ruleForm.status != 4"
          filterable
          reserve-keyword
        >
          <el-option v-for="item in bomSelList" :key="item.bomCode" :label="item.bomCode" :value="item.bomCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="委外数量">
        <el-input
          clearable
          v-model="ruleForm.subcontractingWeight"
          @keyup.enter="subcontractingWeightkeyup"
          :disabled="ruleForm.status != 1"
        />
      </el-form-item>
      <el-form-item label="需求时间">
        <el-input clearable v-model="ruleForm.demandTime" disabled />
      </el-form-item>
      <el-form-item label="加工单价" prop="machiningPrice">
        <el-input type="number" :min="0" clearable v-model="ruleForm.machiningPrice" :disabled="props.db" />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierName">
        <el-input clearable v-model="ruleForm.supplierName" @click="supplierIsShow = true" :disabled="props.db" />
      </el-form-item>
      <el-form-item
        label="加工商"
        prop="converterDict"
        v-if="
          ruleForm.status == 7 ||
          ruleForm.status == 8 ||
          ruleForm.status == 9 ||
          ruleForm.status == 10 ||
          ruleForm.status == 11
        "
      >
        <el-input
          :suffix-icon="Search"
          clearable
          @click="converterShow = true"
          v-model="ruleForm.converterDict"
          :disabled="ruleForm.status != 7"
        />
      </el-form-item>
      <el-form-item
        label="委外合同号"
        prop="subcontractingContractNum"
        v-if="
          ruleForm.status == 7 ||
          ruleForm.status == 8 ||
          ruleForm.status == 9 ||
          ruleForm.status == 10 ||
          ruleForm.status == 11
        "
      >
        <el-input clearable v-model="ruleForm.subcontractingContractNum" />
      </el-form-item>
      <div class="flex-items-center">
        <label class="remarkLabel">备注</label>
        <el-input
          disabled
          autosize
          clearable
          v-model="ruleForm.remark"
          :rows="2"
          type="textarea"
          placeholder="请输入内容"
          :input-style="{ width: '95%' }"
        />
      </div>
      <div
        class="mt20"
        v-if="
          ruleForm.status == 7 ||
          ruleForm.status == 8 ||
          ruleForm.status == 9 ||
          ruleForm.status == 10 ||
          ruleForm.status == 11
        "
      >
        <el-form-item label="合同上传" prop="contractUrl">
          <ImageUpload v-model="ruleForm.contractUrl" v-if="ruleForm.status == 11" />
          <ImagePreview :src="ruleForm.contractUrl" v-else />
        </el-form-item>
      </div>
    </el-form>
    <p-table-add title="物料信息" @add="addTable" @remove="remove" />
    <el-button type="warning" @click="isTypeList">类型</el-button>
    <el-table stripe border :data="ruleForm.orderMaterialDetailList" style="margin-top: 10px">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" width="70" type="index" />
      <!-- <el-table-column label="类别" prop="materialTypeDict" width="150" /> -->
      <el-table-column label="物料名称" prop="materialName" width="auto" />
      <el-table-column label="物料编码" prop="materialCode" width="auto" />
      <el-table-column label="物料规格" prop="materialSpec" width="auto" />
      <!-- <el-table-column label="物料类别" prop="materialCategoryDict" width="150" /> -->
      <!-- <el-table-column label="占比" prop="bomDetailDosage" width="120" /> -->
      <el-table-column label="库存量" prop="stockNum" width="auto" />
      <el-table-column label="单位" prop="materialUnitDict" width="auto" />
      <!-- <el-table-column label="计算量 " width="120">
        <template #default="scope">
          {{ ((ruleForm.subcontractingWeight * (scope.row.bomDetailDosage || 1)) / 100).toFixed(2) }}
        </template>
      </el-table-column> -->
      <el-table-column label="需求量 " align="center" width="120">
        <template #default="scope">
          <div class="inputClass">
            <el-input
              type="number"
              oninput="if(value<=0)value=''"
              clearable
              v-model="scope.row.plannedWeight"
            ></el-input>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 物料弹窗 -->
    <Material
      :is-show="materialShow"
      :dict="[
        { label: '半成品', value: '3' },
        { label: '成品', value: '4' }
      ]"
      @preservation="materialSelsct"
      @cancel="materialShow = false"
    />
    <!-- BOM -->
    <p-XiaoheDialog :dialogVisible="bomShow" title="BOM选择" @close="bomShow = false" width="50%">
      <template #body>
        <Bom :bomType="ruleForm.materialType" @preservation="bomSelsct" @cancel="bomShow = false"
      /></template>
    </p-XiaoheDialog>
    <Supplier :is-show="supplierIsShow" @preservation="supplierSub" @cancel="supplierIsShow = false" />
    <!-- 生产计划 -->
    <Production
      :is-show="productionOrderIsShow"
      @preservation="productionSub"
      @cancel="productionOrderIsShow = false"
    />

    <!-- 加工商 -->
    <p-XiaoheDialog :dialogVisible="converterShow" title="加工商" @close="converterShow = false" width="50%">
      <template #body> <Converter @preservation="converterSelsct" @cancel="converterShow = false" /></template>
    </p-XiaoheDialog>
    <Material
      :is-show="materialShow2"
      :dict="[
        {
          label: '原料',
          value: '1'
        },
        {
          label: '半成品',
          value: '3'
        },
        {
          label: '辅料',
          value: '2'
        },
        {
          label: '成品',
          value: '4'
        }
      ]"
      :bdb="false"
      @preservation="materialSub2"
      @cancel="materialShow2 = false"
    />
  </div>
</template>

<style scoped>
.app-container {
  width: 100%;
}

.app-container /deep/ .el-input__inner {
  width: 220px !important;
}
.inputClass /deep/ .el-input__inner {
  width: 100px !important;
}
</style>
